// 购物车中间件
let { veifyToken } = require('../utils/token')

// 购物车添加使用----->校验数据类型
let add = (req, res, next) => {
  let { uid, gid } = req.body
  // 校验current
  if (!uid) return next({ code: 0, message: '参数uid必须传递' });
  if (!gid) return next({ code: 0, message: '参数gid必须传递' });
  next();
}

// 获取购物车列表
let list = (req, res, next) => {
  let { uid } = req.query
  // 校验current
  if (!uid) return next({ code: 0, message: '参数uid必须传递' });
  next();
}

// 移除购物车商品--->校验数据
let del = (req, res, next) => {
  let { opt, id } = req.body;

  if (!opt) return next({ code: 0, message: '移除购物车失败,参数opt必填' })
  if (!/^(id|some|any)$/.test(opt)) return next({ code: 0, message: '移除购物车失败,参数opt格式错误' })
  if (opt === 'id' && !id) return next({ code: 0, message: '移除单个购物车失败,参数id必填' })

  next();
}

let upSel = (req, res, next) => {
  let { opt, id, state } = req.query;

  if (!opt) return next({ code: 0, message: '修改购物车失败,参数opt必填' })
  if (!/^(id|any)$/.test(opt)) return next({ code: 0, message: '修改购物车失败,参数opt格式错误' })
  if (opt === 'id' && !id) return next({ code: 0, message: '修改单个购物车失败,参数id必填' })

  if (!state) return next({ code: 0, message: '修改购物车失败,参数state必填' })
  if (!/^(1|0)$/.test(state)) return next({ code: 0, message: '修改购物车失败,参数state格式错误' })

  next();
}


let subM = (req, res, next) => {
  let { id, uid } = req.query;

  if (!id) return next({ code: 0, message: '修改购物车失败,参数id必填' })
  if (!uid) return next({ code: 0, message: '修改购物车失败,参数uid必填' })

  next();
}

// token校验中间件
let tokenTest = async (req, res, next) => {
  // 接受id参数并进行校验
  let uid = req.query.uid ?? req.body.uid;
  // 接受token
  let token = req.headers.authorization
  // 不为空校验
  if (!token) return next({ code: 2, message: 'token必须传递' });

  // token校验
  let { status, info, message } = await veifyToken(token);
  if (status != 1) return next({ code: 0, message: `token失效--${message}` })
  // 解析token后 token的正确校验
  if (info.id != uid) return next({ code: 0, message: `token有误` })
  next()
}

module.exports = {
  add, list, del, upSel, subM,tokenTest
}